package com.lgl.scs.userIndex.controller;

import com.github.pagehelper.PageInfo;
import com.lgl.scs.base.controller.BaseController;
import com.lgl.scs.information.service.AddressService;
import com.lgl.scs.system.service.DictionariesService;
import com.lgl.scs.userIndex.service.ServiceOrderService;
import com.lgl.scs.userIndex.service.UserRateService;
import com.lgl.scsapi.system.model.AppUser;
import com.lgl.scsapi.system.model.PageData;
import com.lgl.scsapi.util.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统前台部分首页部分
 */
@Slf4j
@RestController
@RequestMapping(value="/userIndex")
public class ScsIndexController extends BaseController {
	@Resource(name="addressService")
	private AddressService addressService;
	@Resource(name="dictionariesService")
	private DictionariesService dictionariesService;
	@Resource(name="serviceOrderService")
	private ServiceOrderService serviceOrderService;
	@Resource(name="userRateService")
	private UserRateService userRateService;

	//请求主页的页面数据
	@RequestMapping(value="/initPageInfo",produces="application/json;charset=UTF-8")
	public Object initPageInfo() {
		PageData pd = this.getPageData();
		List<PageData> areaList = null, serviceTypeList = null;
		//取得城市ID
		Object cityCodeObj = pd.remove("cityCode");
		String cityCode = cityCodeObj == null ? null : cityCodeObj.toString(),
				cityName = pd.getString("cityName"), parentId = pd.getString("parentId");
		//如果城市编码和城市名称都为空，则不查询区域信息
		boolean isQueryArea = (!StringUtils.hasText(cityCode) || "null".equalsIgnoreCase(cityCode)) &&
				(!StringUtils.hasText(cityName) || "null".equalsIgnoreCase(cityName));
		try {
			if (!isQueryArea) {
				if (StringUtils.hasText(cityName) && cityName.endsWith("市")) {
					cityName = cityName.substring(0, cityName.length() - 1);
				}
				cityCode = Constants.hotCityMap.get(cityName);
				if (!StringUtils.hasText(cityCode)) {
					cityCode = addressService.findCityIdByName(cityName);
				}
			}
			//如果redis不可用
			if (!Constants.REDIS_IS_USABLE) {
				serviceTypeList = listType(pd, parentId);
				if (!isQueryArea) {
					areaList = listArea(cityCode, pd);
				}
				return returnInitPage(areaList, serviceTypeList, cityCode);
			}
			if (!isQueryArea) {
				//获取该城市下的所有的区县
				if (StringUtils.hasText(cityCode)){
					pd.remove("cityName");
					pd.put("cityCode",cityCode);
				}
				//注：此方法会把pd中的参数清空，并只保留了cityCode参数，故在下面手动重新往pd里添加parentId参数
				areaList = addressService.listAllArea(pd);
			}
			if (StringUtils.hasText(parentId)) {
				pd.put("parentId",parentId);
				serviceTypeList = dictionariesService.listDictionaries(pd);
			}
		} catch (Exception e) {
			//如果是redis连接异常
			if (e instanceof PoolException) {
				Constants.REDIS_IS_USABLE = false;
			}
			//如果缓存中没有，则从数据库中取
			serviceTypeList = listType(pd, parentId);
			if (!isQueryArea) {
				areaList = listArea(cityCode,pd);
			}
			log.error(e.toString(),e);
		}
		return returnInitPage(areaList, serviceTypeList, cityCode);
	}

	/**
	 * 返回initPageInfo方法的数据
	 * @param areaList 区域集合
	 * @param serviceTypeList 服务类型集合
	 * @param cityCode 城市编码
	 * @return 包含区域集合、服务类型集合、状态、城市编码的map对象
	 */
	private Map<String, Object> returnInitPage(List<PageData> areaList, List<PageData> serviceTypeList, String cityCode) {
		Map<String, Object> resultMap = new HashMap<String, Object>(4);
		resultMap.put("areaList", areaList);
		resultMap.put("serviceTypeList", serviceTypeList);
		resultMap.put("status", "0");
		resultMap.put("cityCode", cityCode);
		return resultMap;
	}
	/**
	 * 加载区县
	 * @param cityCode 城市编码
	 * @param pd PageData对象
	 */
	private List<PageData> listArea(String cityCode,PageData pd){
		if (!StringUtils.hasText(cityCode)){
			return null;
		}
		pd.clear();
		pd.put("cityCode", cityCode);
		return addressService.listAllArea(pd);
	}
	/**
	 * 加载服务类型数据
	 * @param pd PageData对象
	 * @param parentId 数据字典低级ID
	 */
	private List<PageData> listType(PageData pd, String parentId) {
		if (!StringUtils.hasText(parentId)){
			return null;
		}
		pd.clear();
		pd.put("parentId", parentId);
		return dictionariesService.listDictionaries(pd);
	}
	/**
	 * 请求主页的页面数据
	 */
	@RequestMapping(value="/queryServiceOrder",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
	public Object queryServiceOrder() {
		PageData pd = this.getPageData();
		PageInfo orderPage = null;
		//取得城市ID
		String cityCode = pd.getString("cityCode");
		if (!StringUtils.hasText(cityCode)) {
			cityCode = Constants.hotCityMap.get(pd.getString("cityName"));
			if (!StringUtils.hasText(cityCode)) {
				cityCode = addressService.findCityIdByName(pd.getString("cityName"));
			}
		}

		int pageNo = pd.getInt("currentPage"), pageSize = pd.getInt("pageSize");
		try {
		    //使用redis时，需要将非未抢单状态的的单据删除
			/*if (redisService.redisIsUsable) {
				String redisServiceKey = Constants.CO_SERVICE + cityCode;
				int startRow = (pageNo - 1) * pageSize;
				//从REDIS缓存中获取服务订单数据
				serviceOrderList = redisService.oLrange(redisServiceKey,startRow,startRow + pageSize);
				if (serviceOrderList == null || serviceOrderList.isEmpty()) {
					orderPage = getOrderPage(pd,cityCode,pageNo,pageSize);
				}else {
					String tp = redisService.get(Constants.CO_SERVICE_TP + cityCode);
					serviceOrderList = redisService.oLrange(redisServiceKey,startRow,startRow + pageSize);
					orderPage = new PageInfo(serviceOrderList);
					orderPage.setTotal(StringUtils.hasText(tp) ? Long.parseLong(tp) : 0);
				}
			}else {*/
				//如果redis出现异常，则从数据库中取
				orderPage = getOrderPage(pd,cityCode, pageNo, pageSize);
			//}
		} catch (Exception e) {
			//如果是redis连接异常
			/*if (e instanceof PoolException) {
				redisService.redisIsUsable = false;
			}
			//如果redis出现异常，则从数据库中取
			orderPage = getOrderPage(pd, cityCode,pageNo,pageSize);*/
            log.error(e.toString(),e);
		}
		return orderPage;
	}

	/**
	 * 获取服务订单数据
	 * @param pd PageData对象
	 * @param cityCode 城市编码
	 * @param pageNo 当前页号
	 * @param pageSize 每页显示的记录数
	 * @return 含分页数据、记录数、页号及其它相关数据的PageInfo对象
	 */
	private PageInfo getOrderPage(PageData pd,String cityCode,int pageNo,int pageSize){
		pd.put("cityCode", cityCode);
		pd.put("soStatus", "0");
		AppUser loginUser = getSessionAppUser();
		if (loginUser != null){
			//如果当前用户已登录，则在主页上不显示用户自己发布的订单
			pd.put("notEqualsUser",loginUser.getUserId());
		}
		return serviceOrderService.pageServiceOrder(pageNo,pageSize,pd);
	}
	/**
	 * 获取所有服务类型
	 */
	@RequestMapping(value="/listDictionaries",produces="application/json;charset=UTF-8")
	public Object listDictionaries(){
		return dictionariesService.listDictionaries(getPageData());
	}
	/**
	 * 查看订单
	 */
	@RequestMapping(value="/showOrderDetail")
	public Object showOrderDetail() {
		PageData pd = this.getPageData();
		String osId = pd.getString("oid");
		pd.clear();
		pd.put("soBillNumber", osId);
		return serviceOrderService.getServiceOrderById(pd);
	}

	/**
	 * 获取订单相关的评论
	 */
	@RequestMapping(value = "/listRateByOrder",produces="application/json;charset=UTF-8")
	public Object listRateByOrder() {
		return userRateService.listRateByOrder(getPageData());
	}
	/**
	 * 设置redis可用
	 */
	@RequestMapping(value = "/setRedisEnable",produces="application/json;charset=UTF-8")
	public Object setRedisEnable() {
		Constants.REDIS_IS_USABLE = true;
		return "OK";
	}
	/**
	 * 获取所有城市
	 */
	@RequestMapping(value = "/listAllCities",produces="application/json;charset=UTF-8")
	public Object listAllCities() {
		return addressService.listAllCities(getPageData());
	}
	/**
	 * 通过城市拼音首字母获取城市
	 */
	@RequestMapping(value = "/listCitiesByWords",produces="application/json;charset=UTF-8")
	public Object listCitiesByWords() {
		return addressService.listCitiesByWords(getPageData());
	}

}